package com.zcsy.manage.distribution.controller.mall;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.DistributionConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.util.Globals;
import com.zcsy.commons.util.MD5Util;
import com.zcsy.manage.distribution.common.CommonUtils;
import com.zcsy.manage.distribution.common.EncryptionUtil;
import com.zcsy.manage.distribution.common.OrderUtil;
import com.zcsy.manage.distribution.common.StringUtil;
import com.zcsy.manage.distribution.service.base.CCommonTokenService;
import com.zcsy.manage.distribution.service.base.CShopInfoService;
import com.zcsy.manage.distribution.service.mall.CIOrderInfoDetailService;
import com.zcsy.manage.distribution.service.mall.CIOrderInfoService;
import com.zcsy.manage.distribution.service.system.CIRoleCellService;
import com.zcsy.manage.distribution.service.system.IDUserService;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.model.dmall.vo.OrderDetailVo;
import com.zcsy.manage.model.dmall.vo.OrderInfoVo;
import com.zcsy.manage.model.mall.OrderInfo;
import com.zcsy.manage.model.system.RoleUser;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.service.push.impl.PushServiceImpl;
import com.zcsy.manage.service.system.IRoleService;
import com.zcsy.manage.service.system.IUserService;

/**
 * @Title:OrderInfoController
 * @Package： com.zcsy.manage.distribution.controller.mall
 * @Description:订单控制层
 * @author wangj
 * @date 2016年5月27日下午4:04:21
 * @version 1.0
 * @see JDK1.7.0_67
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 */

@Controller
@RequestMapping(value = "/orderInfo")
public class OrderInfoController {

	@Autowired
	private CIOrderInfoService orderInfoService;
	
	@Autowired
	private CIOrderInfoDetailService orderDetailService;
	
	@Autowired
	private IDUserService userService;
	
	@Autowired
	private CCommonTokenService commonTokenService;
	
	@Autowired
	private CShopInfoService shopInfoService;
	
	@Autowired
	private CIRoleCellService cellService;
	
	@Autowired
	private IRoleService roleService;
	
	@Autowired
	PushServiceImpl pushService;
	
	@Autowired
	private IUserService useService;
	
    
	/**
	 * @Description 获取订单列表并分页显示
	 * @param pNo
	 *            当前页
	 * @param state
	 *            客户端的订单状态(多个用逗号隔开)
	 * @param token
	 *            客户端用户token
	 * @return 订单列表
	 * @author liuying 1075817474@qq.com
	 * @date 2016年6月17日
	 * @see
	 */
	@RequestMapping(value = "selectOrder")
	@ResponseBody
	public RequestJson selectOrder(String beginDate,
			String endDate, String cellId, Integer pNo, String state, String token ) throws RuntimeException{
		
		RequestJson result = new RequestJson();
		
		if (pNo == null || pNo < 1) {
			pNo = DistributionConstants.PAGE_NO;
		}
		
		List<OrderInfoVo> orderInfos = null;
		
		if (state == null) {
			state = String.valueOf(DistributionConstants.DIS_ORDER_STATE_WAIT_FOR_SENDER);
		}
		//查询条件
		Map<String, Object> params = new HashMap<String, Object>();
		
		//日期中只有一个为空，则返回错误
		if(!StringUtil.isValid(beginDate) && StringUtil.isValid(endDate)) {
			result.setResultCode(DistributionConstants.NO_BEGIN_TIME);
			result.setMsg("请输入开始时间");
			result.setSuccess(false);
			return result;
		}
		
		if(StringUtil.isValid(beginDate) && !StringUtil.isValid(endDate)) {
			result.setResultCode(DistributionConstants.NO_END_TIME);
			result.setMsg("请输入结束时间");
			result.setSuccess(false);
			return result;
		}
		
		if(StringUtil.isValid(beginDate)){
			params.put("beginTime", beginDate);
		}
		
		if(StringUtil.isValid(endDate)){
			params.put("endTime", endDate);
		}
		
		//根据token查用户登录名
		commonTokenService.OrderInteractState(token , result);
		if (result.isSuccess()) {
			
			CommonToken commonToken = commonTokenService.selectByToken(token);
			User loginUser = userService.selectByLoginName(commonToken.getAccount());
			//读取相关角色权限
			List<RoleUser> roleIdList = roleService.getRoleIdByUserId(loginUser.getId());
			List<String> roleIds = new ArrayList<String>();
			Set<String> menus = null;
			for(RoleUser item :roleIdList){
				roleIds.add(item.getRoleId());
				
				List<String> roleMenu = userService.selectRoleMenu(item.getRoleId());
				//去重
                if(menus == null) {
                	menus = new HashSet<String>() ;
                }
                
                menus.addAll(roleMenu);
			}
			List<Map<String, Object>> cells;
			
			//如果选了小区，那么就查所选小区，否则就查有权限的所有小区
			if(cellId != null && cellId.length() > 0){
				if(menus == null || menus.size() == 0){
	            	result.setSuccess(false);
	    			result.setResultCode(DistributionConstants.PASSWORD_FALSE);
	    			result.setMsg("该用户没有任何权限，请联系管理员！");
	    			return result;
	            }
				
				cells = new ArrayList<Map<String,Object>>();
				Map<String, Object> maps = new HashMap<String, Object>();
				maps.put("cell_id", cellId);
				cells.add(maps);
				params.put("cells", cells);
			}else{
				cells = cellService.selectByRole(roleIds);
				if(menus == null || menus.size() == 0 || cells == null || cells.size() == 0){
	            	result.setSuccess(false);
	    			result.setResultCode(DistributionConstants.PASSWORD_FALSE);
	    			result.setMsg("该用户没有任何权限，请联系管理员！");
	    			return result;
	            }
				
				params.put("cells", cells);
			}
			boolean haveQd = false;//是否有抢单权限
			boolean havePd = false;//是否有派单权限
			for(String item :menus){
				if(item.equals(DistributionConstants.DISTRIBUTION_ONE)){
					haveQd = true;
				}else if(item.equals(DistributionConstants.DISTRIBUTION_TWO)){
					havePd = true;
				}
			}
			
			params.put("haveQd", haveQd);
			params.put("havePd", havePd);
			
			if(!haveQd && !havePd){
				result.setSuccess(false);
    			result.setResultCode(DistributionConstants.PASSWORD_FALSE);
    			result.setMsg("该用户没有查阅订单权限！");
    			return result;
			}
			
			// 此处添加PageHelper将会走拦截器，进行分页，分页方法只针对紧跟着PageHelper的查询方法有效
			PageHelper.startPage(pNo, DistributionConstants.PAGE_SIZE);
			
			if(state.equals(DistributionConstants.DIS_ORDER_STATE_ALL+"")){
				//state传进来是"0"时
				//全部订单
				params.put("senderAccount", commonToken.getAccount());
				orderInfos = orderInfoService.selectAllOrderListForDistribution(params);
				
			} else if (state.equals(DistributionConstants.DIS_ORDER_STATE_WAIT_FOR_SENDER+"")){
				//待指派订单
				//客户端的待指派订单条件
				params.put("state", DistributionConstants.DIS_ORDER_STATE_WAIT_FOR_SENDER);
				orderInfos = orderInfoService.selectByStateAndSenderAccount(params);
				
			} else if (state.equals(DistributionConstants.DIS_ORDER_STATE_WAIT_FOR_SENDING+"")){
				//待发货订单
				//客户端的待指派订单条件
				params.put("state", DistributionConstants.DIS_ORDER_STATE_WAIT_FOR_SENDING);
				params.put("senderAccount", commonToken.getAccount());
				
				orderInfos = orderInfoService.selectByStateAndSenderAccount(params);
				
			} else if (state.equals(DistributionConstants.DIS_ORDER_STATE_SENDING+"")){
				//配送中订单
				//客户端的待指派订单条件
				params.put("state", DistributionConstants.DIS_ORDER_STATE_SENDING);
				params.put("senderAccount", commonToken.getAccount());
				
				orderInfos = orderInfoService.selectByStateAndSenderAccount(params);
				
			} else if (state.equals(DistributionConstants.DIS_ORDER_STATE_DONE+"")){
				//已完成订单
				//客户端的待指派订单条件
				params.put("state", DistributionConstants.DIS_ORDER_STATE_DONE);
				params.put("senderAccount", commonToken.getAccount());
				
				orderInfos = orderInfoService.selectByStateAndSenderAccount(params);
				
			} else if (state.equals(DistributionConstants.DIS_ORDER_STATE_WAIT_FOR_SENDER+","+DistributionConstants.DIS_ORDER_STATE_WAIT_FOR_SENDING+","+DistributionConstants.DIS_ORDER_STATE_SENDING)){
				//首页显示的订单
				params.put("senderAccount", commonToken.getAccount());
				orderInfos = orderInfoService.selectAllWaitForDealOrderListForDistribution(params);
			} else {
				//默认查询首页显示的订单
				params.put("senderAccount", commonToken.getAccount());
				orderInfos = orderInfoService.selectAllWaitForDealOrderListForDistribution(params);
			}
			
			for(OrderInfoVo item : orderInfos){
				if(org.springframework.util.StringUtils.isEmpty(item.getShopId())){
					item.setShopAddress(Constants.DLIFE);
				}else if(org.springframework.util.StringUtils.isEmpty(item.getShopAddress())){
					item.setShopAddress(item.getShopName());
				}
				
				if(!org.springframework.util.StringUtils.isEmpty(item.logoUrl)){
					item.logoUrl = Globals.getConfig("imageurl") + item.logoUrl;
				}
			}
			
			//分页
			PageInfo<OrderInfoVo> infosP = new PageInfo<OrderInfoVo>(orderInfos);
			result.setObj(infosP);
			OrderUtil.successData(result);
			result.setMsg("成功获取数据");
			
		}

		return result;
	}
	
	/**
	 * @Title: orderDetails
	 * @Description: 获取订单详情
	 * @param ordernumber
	 *            订单编号
	 * @param token
	 *            会话id
	 * @return RequestJson
	 * @throws
	 */
	@RequestMapping(value = "orderinfo")
	@ResponseBody
	public RequestJson orderDetails(String ordernumber, String token) {
		RequestJson result = new RequestJson();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("kordernumber", ordernumber);
		params.put("token", token);
		
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dordernumber = (String) deparams.get("kordernumber");
		String dtoken = (String) deparams.get("token");

		commonTokenService.OrderInteractState(dtoken , result);
		if (result.isSuccess()) {
			List<OrderDetailVo> list = orderInfoService.selectOrderDetailInfo(dordernumber);

			OrderUtil.successData(result);
			result.setMsg("成功获取数据");
			result.setObj(list);
		}

		return result;
	}

	/**
	 * @Title: updateState
	 * @Description: 更新订单状态（配送完成之后）
	 * @param ordernumber
	 *            订单编号
	 * @return RequestJson
	 * @author wangj 1157360454@qq.com
	 * @date 2016年5月25日
	 * @throws
	 */

	@RequestMapping(value = "updateState")
	@ResponseBody
	public RequestJson updateState(String ordernumber, String token) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("ordernumber", ordernumber);
		params.put("token", token);

		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dordernumber = (String) deparams.get("ordernumber");
		String dtoken = (String) deparams.get("token");
		RequestJson result = new RequestJson();

		commonTokenService.OrderInteractState(dtoken , result);
		if (result.isSuccess()) {
			Integer state = orderInfoService.selectByOrderNumber(dordernumber).getState();
			// 订单状态为3是配送中，才能改变状态
			if (state.equals(DistributionConstants.IS_DISTRIBUTING)) {
				OrderInfo orderInfo = new OrderInfo();
				orderInfo.setOrderNumber(dordernumber);
				orderInfoService.updateState(orderInfo);
				
				OrderUtil.successData(result);
				result.setMsg("配送完成！");

			} else {
				
				result.setMsg("订单不在配送中，无法更改状态");
				result.setResultCode(DistributionConstants.NOT_DISTRIBUTING);
				result.setSuccess(false);
			}

		}
		
		return result;
	}

	/**
	 * @Title: showReport
	 * @Description: 展示报表
	 * @param beginDate
	 *            开始时间
	 * @param endDate
	 *            截至时间
	 * @param cellId
	 *            小区id
	 * @param state
	 *            订单状态
	 * @param token
	 *            会话id
	 * @return RequestJson
	 * @throws ParseException
	 * @author wangj 1157360454@qq.com
	 * @date 2016年6月17日
	 * @throws
	 */
	@RequestMapping(value = "showReport")
	@ResponseBody
	public RequestJson showReport( String beginDate,
			String endDate, String cellId, Integer state ,String token) throws ParseException {
		RequestJson result = new RequestJson();
 		Map<String, Object> params = new HashMap<String, Object>();
		
		params.put("cellId", cellId);
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);
		params.put("state", state);
		params.put("token", token);
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		
		String dcellId = (String) deparams.get("cellId");
		String dbeginDate = (String) deparams.get("beginDate");
		String dendDate = (String) deparams.get("endDate");
		Integer dstate = (Integer) deparams.get("state");
        String dtoken = (String) deparams.get("token");
		Map<String, Object> map = new HashMap<String, Object>();
		
		CommonToken tokenInfo = commonTokenService.selectByToken(dtoken);
		if (tokenInfo.getId() == null) {
			result.setSuccess(false);
			if (tokenInfo.getTokenMessage() == DistributionConstants.OTHER_DEVICES_LOGIN) {
				result.setResultCode(tokenInfo.getTokenMessage());
				result.setMsg("帐号在其他设备登录");
			}
			if (tokenInfo.getTokenMessage() == DistributionConstants.INVALID_LOGIN) {
				result.setResultCode(tokenInfo.getTokenMessage());
				result.setMsg("用户授权失效请重新登录");
			}
		}else {	
			//获取当前用户菜单权限
			User user = userService.selectByLoginName(tokenInfo.getAccount());
			List<String> menuList = useService.getMenuListByUserId(user.getId());
			
			if(CollectionUtils.isNotEmpty(menuList) && !(menuList.contains(DistributionConstants.DISTRIBUTION_THERE) && (menuList.contains(DistributionConstants.DISTRIBUTION_ONE) || menuList.contains(DistributionConstants.DISTRIBUTION_TWO)))){
				result.setSuccess(false);
				result.setMsg("用户权限不够！");
			}else{
				//必须同时拥有报表权限，和抢单或派单的一种才能查询
				
				//不包含派单权限只能查看自己的订单
				if(!menuList.contains(DistributionConstants.DISTRIBUTION_TWO)){
					map.put("senderAccount", user.getLoginname());
					
				}
				if(dstate == null){
					dstate = DistributionConstants.DIS_ORDER_STATE_ALL; //状态为0，查询所有
				}
				map.put("state", dstate);
				map.put("cellId", dcellId);
				
				
				String begin = ""; //开始时间
				String end = "";   //结束时间
				SimpleDateFormat  time = new SimpleDateFormat("yyyy/MM/dd");

				long days = 0;
				Calendar cal = null;
				String startTime = null;
				
				//第一种情况：开始时间和结束时间都为空，
				if (StringUtils.isEmpty(dbeginDate) && StringUtils.isEmpty(dendDate)) {
					//取当前日期
					cal   =   Calendar.getInstance();
					cal.add(Calendar.DATE,   -1);
					
					
					//前一天
					String endTime = new SimpleDateFormat( "yyyy/MM/dd").format(cal.getTime());
					cal.setTime(time.parse(endTime));  
					long timeOne = cal.getTimeInMillis(); 
					
					//前7天
					cal.add(Calendar.DATE,   -6);
					startTime = new SimpleDateFormat( "yyyy/MM/dd").format(cal.getTime());
					cal.setTime(time.parse(startTime));  
					long timeTwo = cal.getTimeInMillis();   
					
					//取间隔天数
					days=(timeOne-timeTwo)/(1000*3600*24) + 1;
					
					map.put("beginDate", startTime);
					map.put("endDate", endTime);
					
					begin = startTime;
					end = endTime;
					result.setSuccess(true);
					
					//第二种情况：开始时间和结束时间都不为空，
				}else if(StringUtils.isNotEmpty(dbeginDate) && StringUtils.isNotEmpty(dendDate)){
					
					cal = Calendar.getInstance();  
					cal.setTime(time.parse(dbeginDate));  
					long timeOne = cal.getTimeInMillis();
					cal.setTime(time.parse(dendDate));  
					long timeTwo = cal.getTimeInMillis();       
					days=(timeTwo-timeOne)/(1000*3600*24) + 1;

					//方便补零
					startTime = dbeginDate;
					
					//间隔期间超过30天，查询失败
					if(days > 30){
						result.setSuccess(false);
						result.setResultCode(DistributionConstants.NO_RECORD);
						result.setMsg("搜索时间超过30天！");
						//间隔期间小于30天，查询成功
					}else{
						
						map.put("beginDate", dbeginDate);
						map.put("endDate", dendDate);
						
						begin = dbeginDate;
						end = dendDate;
						result.setSuccess(true);
					}
					
					//第三种情况：开始时间不为空，结束时间为空，   
				}else if(StringUtils.isNotEmpty(dbeginDate) && StringUtils.isEmpty(dendDate)){
					/*Calendar cal = Calendar.getInstance();  
				DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
				cal.setTime(df.parse(dbeginDate));
				cal.add(Calendar.DATE,   +30);
				String endTime = new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
				map.put("beginDate", dbeginDate);
				map.put("endDate", endTime);
				
				begin = dbeginDate;
				end = endTime;*/
					result.setSuccess(false);
					result.setResultCode(DistributionConstants.NO_RECORD);
					result.setMsg("请输入结束时间！");
					
					//第四种情况：开始时间为空，结束时间不为空，   	
				}else if(StringUtils.isEmpty(dbeginDate) && StringUtils.isNotEmpty(dendDate)){
					/*Calendar cal = Calendar.getInstance();  
				DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
				cal.setTime(df.parse(dendDate));
				cal.add(Calendar.DATE,   -30);
				String bigenTime = new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
				map.put("beginDate", bigenTime);
				map.put("endDate", dendDate);
				
				begin = bigenTime;
				end = dendDate;*/
					result.setSuccess(false);
					result.setResultCode(DistributionConstants.NO_RECORD);
					result.setMsg("请输入起始时间！");
					
				}
				
				
				
				//根据状态和小区查询报表数
				List<Map<String, Object>> olist = orderInfoService.selectByDate(map);
				// 共配送订单数
				int totalNumber = 0;

				// 总盈利收入
				BigDecimal revenue = new BigDecimal("0");
				
				Map<String, Object> mmMap = new HashMap<String, Object>();
				
				//无订单记录
				if(olist == null || olist.size() ==0){
					mmMap.put("revenue", revenue);
					mmMap.put("totalNumber", totalNumber);
					result.setSuccess(false);
					result.setResultCode(DistributionConstants.NO_RECORD);
					result.setMsg("无记录！");
					result.setObj(mmMap);
					
					//有订单记录	
				}else {
					
					//list装入所有map的value
					List<Object> list = new ArrayList<Object>();
					for (Map<String, Object> mapTwo : olist) {
						Set set = mapTwo.keySet();
						Iterator it = set.iterator();
						while (it.hasNext()) {
							String key = (String) it.next();
							String value = mapTwo.get(key).toString();
							list.add(value);
						}
						
					}
					
					
					if(result.isSuccess()){
						
						List<OrderInfo> orderInfos = orderInfoService.selectOrder(map);
						
						//循环得到总金额
						for (OrderInfo orderInfo : orderInfos) {
							revenue = revenue.add(orderInfo.getFinalPrice());
						}
						//得到记录的条数
						totalNumber = orderInfos.size();
						
						//无数据的日期补零
						SimpleDateFormat  datetime = new SimpleDateFormat("yyyy-MM-dd");
						List<Map<String, Object>> olistTemp = new ArrayList<Map<String,Object>>();
						int j = 0;
						for (int i = 0; i < days; i++) {
							cal.setTime(time.parse(startTime));
							cal.add(cal.DATE, i);
							Date date = cal.getTime();
							if (!list.contains(datetime.format(date).toString())) {
								Map<String, Object> mapTwo = new HashMap<String, Object>();
								mapTwo.put("date", datetime.format(date));
								mapTwo.put("num", 0);	
								olistTemp.add(mapTwo);
							} else {
								Map<String, Object> mapTwo = olist.get(j);
								mapTwo.put("date", datetime.format(date));
								olistTemp.add(mapTwo);
								j++;
							}
						}
						olist = olistTemp;
						
						List<Map<String, Object>> slist = orderInfoService.selectOrderSender(map);
						Map<String, Object> mMap = new HashMap<String, Object>();
						mMap.put("date", olist);
						mMap.put("sender", slist);
						mMap.put("revenue", revenue);
						mMap.put("totalNumber", totalNumber);
						mMap.put("beginDate", begin);
						mMap.put("endDate", end);
						result.setSuccess(true);
						result.setResultCode(0);
						result.setMsg("查询成功！");
						result.setObj(mMap);
					}
					
				}
			}
			
		}		
	
		return result;
	}

	/**
	 * @Title: createReportLink
	 * @Description: 生成报表及连接地址
	 * @param beginDate
	 * @param endDate
	 * @param cellId
	 * @param state
	 * @param token
	 * @param request
	 * @param response
	 * @return RequestJson
	 * @author wangj 1157360454@qq.com
	 * @date 2016年6月17日
	 * @throws
	 */
	@RequestMapping(value = "createReportLink")
	@ResponseBody
	public RequestJson createReportLink(String beginDate, String endDate,String cellId, Integer state,
			                            String token,HttpServletRequest request, HttpServletResponse response) {
		RequestJson result = new RequestJson();
	
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("cellId", cellId);
		params.put("beginDate", beginDate);
		params.put("endDate", endDate);
		params.put("state", state);
		params.put("token", token);
		
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dcellId = (String) deparams.get("cellId");
		String dbeginDate = (String) deparams.get("beginDate");
		String dendDate = (String) deparams.get("endDate");
		Integer dstate = (Integer) deparams.get("state");
		String dtoken = (String) deparams.get("token");
		
		Map<String, Object> map = new HashMap<String, Object>();
		commonTokenService.OrderInteractState(dtoken , result);
		if (result.isSuccess()) {

			if (StringUtils.isNotEmpty(dcellId)) {
				map.put("cellId", dcellId);
			}
			if (StringUtils.isNotEmpty(dbeginDate)) {
				map.put("beginTime", dbeginDate);
			}
			if (StringUtils.isNotEmpty(dendDate)) {
				map.put("endTime", dendDate);
			}
			map.put("state", dstate);

			// 生成报表
			Date date = new Date();
			SimpleDateFormat simFor = new SimpleDateFormat("yyyyMMdd HH");

			String fileName = MD5Util.string2MD5(dtoken + map.toString() + simFor.format(date))+ ".xlsx";
			SXSSFWorkbook workbook = orderInfoService.createOrderExcel(map);
			File file = new File(CommonUtils.getDistributionReportParentPath(request)
								+ java.io.File.separator + fileName);
			
			if (!file.exists()) {

				if (!file.getParentFile().exists()) {
					file.getParentFile().mkdirs();
				}

				// 保存表格
				OutputStream out = null;
				try {
					out = new FileOutputStream(file);
					workbook.write(out);
					out.flush();
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (out != null)
						try {
							out.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					if (workbook != null)
						workbook.dispose();
				}
			}

			OrderUtil.successData(result);
			result.setMsg("查询成功！");
			result.setObj(DistributionConstants.IP_DIS_REPORTS_EXCEL
							+ CommonUtils.PATH_DISTRIBUTION_EXCELS + java.io.File.separator + fileName);

		}
		
		return result;
	}

	/**
	 * 
	 * @Title: getOrder
	 * @Description: TODO
	 * @param token
	 *            会话id
	 * @param ordernumber
	 *            订单编号
	 * @param senderAccount
	 *            被指派或者抢单人的 登录名
	 * @return RequestJson
	 * @author wangj 1157360454@qq.com
	 * @date 2016年6月17日
	 * @throws
	 */
	@RequestMapping(value = "getOrder")
	@ResponseBody
	public RequestJson getOrder(String token, String ordernumber,String senderAccount) {
		RequestJson result = new RequestJson();
		
		if (senderAccount == null) { // senderid为空，是抢单
			Map<String, Object> params = new HashMap<String, Object>();
			String KEY_TOKENID = "tokenid";
			String KEY_ORDERNUMBER = "ordernumber";
			String KEY_STATE = "state";
			params.put(KEY_TOKENID, token);
			params.put(KEY_ORDERNUMBER, ordernumber);

			Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
			String dtoken = (String) deparams.get(KEY_TOKENID);
			String dordernumber = (String) deparams.get(KEY_ORDERNUMBER);

			Date date = new Date();
			OrderInfo oInfo = new OrderInfo();
			oInfo.setRushTime(date);
			oInfo.setOrderNumber(dordernumber);

			commonTokenService.OrderInteractState(dtoken , result);
			if (result.isSuccess()) {
				// 通过订单id查询该订单senderAccount
				String senderAccountTwo = orderInfoService.selectByOrderNumber(dordernumber).getSenderAccount();

				if (null != senderAccountTwo) {
					result.setMsg("订单已被抢");
					result.setResultCode(DistributionConstants.ORDER_TAKEN);
					result.setSuccess(false);
				} else {

					String loginname = commonTokenService.selectByToken(dtoken).getAccount();
					oInfo.setSenderAccount(loginname);
					orderInfoService.assignOrder(oInfo);
					
					OrderUtil.successData(result);
					result.setMsg("抢单成功！");
				}

			}

		} else { // 指派订单
			Map<String, Object> params = new HashMap<String, Object>();
			String KEY_TOKENID = "tokenid";
			String KEY_ORDERNUMBER = "ordernumber";
			String KEY_SENDID = "senderid";
			String KEY_STATE = "state";
			params.put(KEY_TOKENID, token);
			params.put(KEY_ORDERNUMBER, ordernumber);
			params.put(KEY_SENDID, senderAccount);

			Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
			String dtoken = (String) deparams.get(KEY_TOKENID);
			String dordernumber = (String) deparams.get(KEY_ORDERNUMBER);
			String dsenderAccount = (String) deparams.get(KEY_SENDID);

			OrderInfo oInfo = new OrderInfo();
			oInfo.setOrderNumber(dordernumber);

			commonTokenService.OrderInteractState(dtoken , result);
			if (result.isSuccess()) {
				// 通过订单id查询该订单senderAccount
				OrderInfo orderInfo = orderInfoService.selectByOrderNumber(dordernumber);
				String senderAccountTwo = orderInfo.getSenderAccount();

				if (senderAccountTwo != null && orderInfo.getAssignAccount() == null) {
					result.setMsg("订单已被抢");
					result.setResultCode(DistributionConstants.ORDER_ASSIGN);
					result.setSuccess(false);
				} else {
					Date date = new Date();
					oInfo.setRushTime(date);
					
					CommonToken tokenInfo = commonTokenService.selectByToken(dtoken);
					String loginname = tokenInfo.getAccount();
					oInfo.setAssignAccount(loginname);
					oInfo.setSenderAccount(dsenderAccount);
					orderInfoService.assignOrder(oInfo);

					OrderUtil.successData(result);
					result.setMsg("指派成功！");
				}

			}

		}

		return result;
	}


	/**
	 * @Description 获取该订订单可指派的配送员列表信息<br>
	 * 
	 * @param orderId 订单id
	 * @param token
	 * @return 该订订单可指派的配送员列表信息
	 * @author caiyinli 13277030520@163.com
	 * @date 2016年6月20日
	 * @see 
	 */
	@RequestMapping(value = "getSenders")
	@ResponseBody
	public RequestJson getSenders(String orderNum,String token) {
		RequestJson result = new RequestJson();
		
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			String KEY_TOKEN = "token";
			params.put(KEY_TOKEN, token);
			
			Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
			String dtoken = (String) deparams.get(KEY_TOKEN);
			
			commonTokenService.OrderInteractState(dtoken , result);
			if (result.isSuccess()) {
				CommonToken tokenInfo = commonTokenService.selectByToken(dtoken);
				
				if(tokenInfo != null){
					if(orderNum != null){
						OrderInfo orderInfo = orderInfoService.selectByOrderNumber(orderNum);
						if(orderInfo != null && orderInfo.getCellId() != null){
							//获取具有抢单权限的roleIdList
							List<User> userList = userService.selectByCellId(orderInfo.getCellId());
							if(CollectionUtils.isNotEmpty(userList)){
								result.setObj(userList);
								OrderUtil.successData(result);
							}else{
								OrderUtil.noRecord(result);
								result.setMsg("当前没有可配送人员！");
							}
						}
					}else{
						OrderUtil.noRecord(result);
						result.setMsg("请选择指派订单！");
					}
				}
				
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return result;
	}

	/**
	 * @Title: getCell
	 * @Description: 获取权限之内的小区
	 * @param token
	 *            会话id
	 * @return RequestJson
	 * @author wangj 1157360454@qq.com
	 * @date 2016年6月12日
	 * @throws
	 */
	@RequestMapping(value = "getCells")
	@ResponseBody
	public RequestJson getCell(String token) {
		RequestJson result = new RequestJson();
		
		Map<String, Object> params = new HashMap<String, Object>();
		String KEY_TOKEN = "token";
		params.put(KEY_TOKEN, token);
		
		Map<String, Object> deparams = EncryptionUtil.decrypParams(params);
		String dtoken = (String) deparams.get(KEY_TOKEN);

		commonTokenService.OrderInteractState(dtoken , result);
		if (result.isSuccess()) {
			CommonToken tokenInfo = commonTokenService.selectByToken(dtoken);
			String loginname = tokenInfo.getAccount();
			User loginUser = userService.selectByLoginName(loginname);
			List<RoleUser> roleIdList = roleService.getRoleIdByUserId(loginUser.getId());
			
			List<String> roleIds = new ArrayList<String>();
			for(RoleUser item :roleIdList){
				roleIds.add(item.getRoleId());
			}
			List<Map<String, Object>> cells = cellService.selectByRole(roleIds);
			
			OrderUtil.successData(result);
			result.setMsg("获取成功!");
			result.setObj(cells);
		}
		
		return result;
	}

	/**
	 * @Title: homePage
	 * @Description: 首页4个数据
	 * @param token
	 *            会话id
	 * @return RequestJson
	 * @author wangj 1157360454@qq.com
	 * @date 2016年6月12日
	 * @throws
	 */
	@RequestMapping(value = "homePage")
	@ResponseBody
	public RequestJson homePage(String token) {
		RequestJson result = new RequestJson();
		
		Map<String, Object> param = new HashMap<String, Object>();
		String KEY_TOKEN = "token";
		param.put(KEY_TOKEN, token);
		
		Map<String, Object> deparams = EncryptionUtil.decrypParams(param);
		String dtoken = (String) deparams.get(KEY_TOKEN);

		commonTokenService.OrderInteractState(dtoken , result);
		if (result.isSuccess()) {
			CommonToken tokenInfo = commonTokenService.selectByToken(dtoken);
			String loginname = tokenInfo.getAccount();
			String userId = userService.selectByLoginName(loginname).getId();
			
			// 日期
			Date date = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
					"yyyy-MM-dd");
			String dateTwo = simpleDateFormat.format(date);
			
			//查询条件
			Map<String, Object> params = new HashMap<String, Object>();
			//读取相关角色权限
			List<RoleUser> roleIdList = roleService.getRoleIdByUserId(userId);
			List<String> roleIds = new ArrayList<String>();
			Set<String> menus = null;
			for(RoleUser item :roleIdList){
				roleIds.add(item.getRoleId());
				
				List<String> roleMenu = userService.selectRoleMenu(item.getRoleId());
				//去重
                if(menus == null) {
                	menus = new HashSet<String>() ;
                }
                
                menus.addAll(roleMenu);
			}
			List<Map<String, Object>> cells;

			// 如果选了小区，那么就查所选小区，否则就查有权限的所有小区
			cells = cellService.selectByRole(roleIds);
			if (menus == null || menus.size() == 0 || cells == null
					|| cells.size() == 0) {
				setEmpty(dateTwo, result);
				return result;
			}
			params.put("cells", cells);
			
			boolean haveQd = false;//是否有抢单权限
			boolean havePd = false;//是否有派单权限
			for(String item :menus){
				if(item.equals(DistributionConstants.DISTRIBUTION_ONE)){
					haveQd = true;
				}else if(item.equals(DistributionConstants.DISTRIBUTION_TWO)){
					havePd = true;
				}
			}
			
			params.put("haveQd", haveQd);
			params.put("havePd", havePd);
			if(!haveQd && !havePd){
				setEmpty(dateTwo, result);
				return result;
			}
			
			//取当前日期
			Calendar cal   =   Calendar.getInstance();
			String endTime = new SimpleDateFormat("yyyy/MM/dd").format(cal.getTime());
			//前7天
			cal.add(Calendar.DATE,   -6);
			String startTime = new SimpleDateFormat("yyyy/MM/dd").format(cal.getTime());

			params.put("senderAccount", loginname);
			
			params.put("beginTime", endTime);//今日
			params.put("endTime", endTime);
			Map<String, Object> map = new HashMap<String, Object>();
			params.put("type", DistributionConstants.HOME_WAIT_SENDER);
			map.put("newOrder", orderInfoService.selectCounts(params));
			
			params.put("type", DistributionConstants.HOME_TODAY_ALL);
			map.put("todayAll", orderInfoService.selectCounts(params));
			
			params.put("type", DistributionConstants.HOME_TODAY_DIS);
			map.put("today", orderInfoService.selectCounts(params));
			
			params.put("beginTime", startTime);//本周
			params.put("type", DistributionConstants.HOME_WEEK_DIS);
			map.put("week", orderInfoService.selectCounts(params));
			
			map.put("date", dateTwo);
			
			OrderUtil.successData(result);
			result.setMsg("获取成功");
			result.setObj(map);
		}
		
		return result;
	}
	
	private void setEmpty(String dateTwo , RequestJson result){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("newOrder", 0);
		map.put("today", 0);
		map.put("week", 0);
		map.put("todayAll", 0);
		map.put("date", dateTwo);
		
		OrderUtil.successData(result);
		result.setMsg("获取成功");
		result.setObj(map);
	}

	/**
	 * @Description 推送消息测试用
	 * @param orderId 订单id
	 * @param pushType 推送消息类型 	
	 * public static final int PUSH_TYPE_ONE = 1; //有新的订单待配送
     * public static final int PUSH_TYPE_TWO = 2; //管理员把订单派给了配送员
	 * @return 推送结果	0为成功，none为无可推送用户，其他为推送错误
	 * @author liuying 1075817474@qq.com
	 * @date 2016年6月17日
	 * @see 
	 */
	@RequestMapping(value = "testPush" )
	@ResponseBody
	 public String testPush(String orderId, Integer pushType) {
	 	String result = pushService.pushDistributionMsg(orderId, pushType);
		
	 	return result;
	}

}
